import PubSub from "./PubSub.js";

export default class LearningList extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({mode: "open"})
        this.items = [];
    }

    connectedCallback() {
        this.shadowRoot.innerHTML = `
            <h2>Learning List (学习清单)</h2>
            <ul>
                <!--学习清单展示区，通过Js添加-->
            </ul>
            <style>
                :host { /* <learning-list> */
                    display: block;
                    border: var(--border-width) solid LightSeaGreen;
                    padding: 2rem;
                    border-radius: var(--border-radius);
                } 
                
                h2 {
                    margin-top: 0;
                }   
                
                ul {
                    padding-left: 0;
                    font-size: 1.2rem;
                    color: var(--text-color);
                }
            </style>
        `
        this.ul = this.shadowRoot.querySelector("ul");
        PubSub.subscribe("learning_item_added", this.add.bind(this));

        this.ul.addEventListener("dblclick", this.learning_item_delete.bind(this))
    }
    add(title){
        this.items.push(title);
        this.ul.innerHTML = "";
        this.items.forEach(item=>{
            const li = document.createElement("li");
            li.innerHTML = item;
            this.ul.appendChild(li);
        })

        PubSub.publish("learning_list_updated", this.items);
    }

    learning_item_delete(e){
        const li = e.target.closest("li");
        const title = li.textContent;
        this.items = this.items.filter(item=>item!==title);
        li.remove();
        PubSub.publish("learning_list_updated", this.items);
    }
}

customElements.define('learning-list', LearningList)
